﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Perceiveit.Xml.Converters
{
    public class EnumXConverter<T> : XConverter<T> 
    {
        public EnumXConverter()
        {
            if (typeof(T).IsEnum == false)
                throw new ArgumentException("Can only operate on enumerated types");
        }

        public bool TryParse(string value, out T eval)
        {
            bool success = false;

            try
            {
                eval = (T)Enum.Parse(typeof(T), value, true);
                success = true;
            }
            catch(ArgumentException)
            {
                eval = default(T);
                success = false;
            }
            return success;
        }

        public override T FromString(string value)
        {
            T item;
            if (string.IsNullOrEmpty(value))
                return default(T);
            else if(!TryParse(value, out item))
                return default(T);
            else
                return item;
        }

        public override string ToString(T value)
        {
            return value.ToString();
        }
    }

    public class NullableEnumConverter<T> : XConverter<T?> where T : struct
    {
        public NullableEnumConverter()
        {
            if (typeof(T).IsEnum == false)
                throw new ArgumentException("Can only operate on enumerated types");
        }
    
        public bool TryParse(string value, out T eval)
        {
            bool success = false;

            try
            {
                eval = (T)Enum.Parse(typeof(T), value, true);
                success = true;
            }
            catch (ArgumentException)
            {
                eval = default(T);
                success = false;
            }
            return success;
        }

        public override T? FromString(string value)
        {
            T item;
            if (string.IsNullOrEmpty(value))
                return null;
            else if (!this.TryParse(value, out item))
                return null;
            else
                return item;
        }

        public override string ToString(T? value)
        {
            if (value.HasValue)
                return value.Value.ToString();
            else
                return string.Empty;
        }
    }
}
